import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_getx/app/config/constant.dart';
import 'package:flutter_getx/core/ext_core.dart';
import 'package:flutter_getx/core/utils/log_utils.dart';
import 'package:flutter_getx/utils/cache_utils.dart';
import 'package:sprintf/sprintf.dart';

import 'error_handle.dart';

class AuthInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    //options.contentType = 'application/json';
    String auth = CacheUtils.authorization().nullSafe;
    if (auth.isNotEmpty) {
      options.headers['Authorization'] = auth;
    }
    /*options.headers['device-id'] = Device.getDeviceId();
    if (!Device.isWeb) {
      options.headers['User-Agent'] = 'Mozilla/5.0';
    }*/
    super.onRequest(options, handler);
  }
}

class LoggingInterceptor extends Interceptor {
  late DateTime _startTime;
  late DateTime _endTime;

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    _startTime = DateTime.now();
    lprint('----------Start----------');
    if (options.queryParameters.isEmpty) {
      lprint('RequestUrl: ${options.baseUrl}${options.path}');
    } else {
      lprint(
          'RequestUrl: ${options.baseUrl}${options.path}?${Transformer.urlEncodeMap(options.queryParameters)}');
    }
    lprint('RequestMethod: ${options.method}');
    lprint('RequestHeaders:${options.headers}');
    lprint('RequestContentType: ${options.contentType}');
    lprint('RequestData: ${options.data.toString()}');
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    _endTime = DateTime.now();
    final int duration = _endTime.difference(_startTime).inMilliseconds;
    if (response.statusCode == ExceptionHandle.success) {
      lprint('ResponseCode: ${response.statusCode}');
    } else {
      lprinte('ResponseCode: ${response.statusCode}');
    }
    // 输出结果
    lprintjson(response.data.toString());
    lprint('----------End: $duration ms----------');
    super.onResponse(response, handler);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    lprint('----------Error-----------');
    super.onError(err, handler);
  }
}

class AdapterInterceptor extends Interceptor {
  static const String _kMsg = 'msg';
  static const String _kSlash = "'";
  static const String _kMessage = 'message';

  static const String _kDefaultText = 'No response';
  static const String _kNotFound = 'Not found';

  static const String _kFailureFormat = '{"${Constant.code}":%d,"${Constant.msg}":"%s"}';
  static const String _kSuccessFormat = '{"${Constant.code}":%d,"${Constant.data}":%s,"${Constant.msg}":%s}';

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    final Response r = adapterData(response);
    super.onResponse(r, handler);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    if (err.response != null) {
      adapterData(err.response!);
    }
    super.onError(err, handler);
  }

  Response adapterData(Response response) {
    String result;
    String content = response.data?.toString() ?? '';

    /// 成功时，直接格式化返回
    if (response.statusCode == ExceptionHandle.success ||
        response.statusCode == ExceptionHandle.success_not_content) {
      if (content.isEmpty) {
        content = sprintf(_kSuccessFormat, [response.statusCode, null, _kDefaultText]);
      }
      result = content;
      response.statusCode = ExceptionHandle.success;
    } else {
      if (response.statusCode == ExceptionHandle.not_found) {
        /// 错误数据格式化后，按照成功数据返回
        result = sprintf(_kFailureFormat, [response.statusCode, _kNotFound]);
        response.statusCode = ExceptionHandle.success;
      } else {
        if (content.isEmpty) {
          // 一般为网络断开等异常
          result = content;
        } else {
          String msg;
          try {
            content = content.replaceAll(r'\', '');
            if (_kSlash == content.substring(0, 1)) {
              content = content.substring(1, content.length - 1);
            }
            final Map<String, dynamic> map =
            json.decode(content) as Map<String, dynamic>;
            if (map.containsKey(_kMessage)) {
              msg = map[_kMessage] as String;
            } else if (map.containsKey(_kMsg)) {
              msg = map[_kMsg] as String;
            } else {
              msg = 'Unknown error';
            }
            result = sprintf(_kFailureFormat, [response.statusCode, msg]);
            // 401 token失效时，单独处理，其他一律为成功
            if (response.statusCode == ExceptionHandle.unauthorized) {
              response.statusCode = ExceptionHandle.unauthorized;
            } else {
              response.statusCode = ExceptionHandle.success;
            }
          } catch (e) {
            // lprint('异常信息：$e');
            // 解析异常直接按照返回原数据处理（一般为返回500,503 HTML页面代码）
            result = sprintf(_kFailureFormat, [response.statusCode, 'Service error:(${response.statusCode})']);
          }
        }
      }
    }
    response.data = result;
    // lprint("result=${result}");
    return response;
  }
}
